package com.shenzhen.horselive.common.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Path;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.GenericLifecycleObserver;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.flqy.baselibrary.Session;
import com.flqy.baselibrary.utils.NetworkUtil;
import com.flqy.baselibrary.utils.T;

import com.mozillaonline.providers.DownloadManager;
import com.mozillaonline.providers.downloads.DownloadInfo;
import com.mozillaonline.providers.downloads.Downloads;
import com.shenzhen.horselive.App;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiException;
import com.shenzhen.horselive.base.ActivityCollector;
import com.shenzhen.horselive.widget.CommonDialog;


import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import gun0912.tedbottompicker.util.UCropUtils;
import retrofit2.HttpException;

import static androidx.lifecycle.Lifecycle.State.DESTROYED;

/**
 * Created by ludaiqian on 16/7/7.
 */
public class Utils extends com.flqy.baselibrary.utils.Utils {

    private static CommonDialog reLoginDialog;




    public static void crop(Activity context, Uri source) {
        int color = context.getResources().getColor(R.color.textColorPrimary);
        UCropUtils.start(context, source, Uri.fromFile(newTempFile(context)), com.flqy.baselibrary.utils.Utils.getColorPrimary(context), color);
    }

    public static void crop(Fragment context, Uri source) {
        int color = context.getResources().getColor(R.color.textColorPrimary);
        UCropUtils.start(context, source, Uri.fromFile(newTempFile(context.getContext())), com.flqy.baselibrary.utils.Utils.getColorPrimary(context.getActivity()), color);
    }

    public static void ignoreMenuLongClick(final Activity context, final int menuId) {
        App.getInstance().post(new Runnable() {
            @Override
            public void run() {
                if (context == null) {
                    return;
                }
                View v = context.findViewById(menuId);
                if (v != null) {
                    v.setOnLongClickListener(new View.OnLongClickListener() {
                        @Override
                        public boolean onLongClick(View v) {
                            return true;
                        }
                    });
                }
            }
        });

    }

    /**
     * 检查手机上是否安装了指定的软件
     *
     * @param context
     * @param packageName：应用包名
     * @return
     */
    public static boolean isPackageInstalled(Context context, String packageName) {
        // 获取packagemanager
        final PackageManager packageManager = context.getPackageManager();
        // 获取所有已安装程序的包信息
        List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
        // 用于存储所有已安装程序的包名
        List<String> packageNames = new ArrayList<String>();
        // 从pinfo中将包名字逐一取出，压入pName list中
        if (packageInfos != null) {
            for (int i = 0; i < packageInfos.size(); i++) {
                String packName = packageInfos.get(i).packageName;
                packageNames.add(packName);
            }
        }
        // 判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
        return packageNames.contains(packageName);
    }

    public static String parseMessage(Throwable e) {
        if (NetworkUtil.isNetworkAvailable()) {
            if (e instanceof ApiException) {
                return e.getMessage();


            } else if (e instanceof HttpException) {
                HttpException httpException = (HttpException) e;
                if (httpException.code() == 401) {
                    User.get().loginOut();
                    ActivityCollector.removeAllActivity();
//                    LoginActivity.launch(App.getInstance());
                    return "当前登录失效,请从新登录";
                } else {
                    return App.getInstance().getString(R.string.request_failed_tips);
                }
            } else {
                return App.getInstance().getString(R.string.request_failed_tips);
            }
        } else {
            return App.getInstance().getString(R.string.no_network_tips);
        }
    }

    public static boolean contain(String[] valueArray, String value) {
        for (String v : valueArray) {
            if (value.equals(v)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 获取单个文件的MD5值！
     *
     * @param file
     * @return
     */
    public static String getFileMD5(File file) {
        if (!file.isFile()) {
            return null;
        }
        MessageDigest digest = null;
        FileInputStream in = null;
        byte buffer[] = new byte[1024];
        int len;
        try {
            digest = MessageDigest.getInstance("MD5");
            in = new FileInputStream(file);
            while ((len = in.read(buffer, 0, 1024)) != -1) {
                digest.update(buffer, 0, len);
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return bytesToHexString(digest.digest());
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void openFile(Context context, File path) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Uri uriForFile = FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", path);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(uriForFile, context.getContentResolver().getType(uriForFile));
        } else {
            intent.setDataAndType(Uri.fromFile(path), getMIMEType(path));
        }
        try {
            context.startActivity(intent);
        } catch (Exception var5) {
            var5.printStackTrace();
            Toast.makeText(context, "没有找到打开此类文件的程序", Toast.LENGTH_SHORT).show();
        }
    }

    private static String getMIMEType(File var0) {
        String var1 = "";
        String var2 = var0.getName();
        String var3 = var2.substring(var2.lastIndexOf(".") + 1, var2.length()).toLowerCase();
        var1 = MimeTypeMap.getSingleton().getMimeTypeFromExtension(var3);
        return var1;
    }

    /**
     * 方法描述：判断某一Service是否正在运行
     *
     * @param context     上下文
     * @param serviceName Service的全路径： 包名 + service的类名
     * @return true 表示正在运行，false 表示没有运行
     */
    public static boolean isServiceRunning(Context context, String serviceName) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> runningServiceInfos = am.getRunningServices(200);
        if (runningServiceInfos.size() <= 0) {
            return false;
        }
        for (ActivityManager.RunningServiceInfo serviceInfo : runningServiceInfos) {
            if (serviceInfo.service.getClassName().equals(serviceName)) {
                return true;
            }
        }
        return false;
    }

    public static <T> boolean isEmpty(Collection<T> list) {
        return list == null || list.size() == 0;
    }

    public static <K, V> boolean isEmpty(Map<K, V> map) {
        return map == null || map.size() == 0;
    }


    public static boolean hasEmpty(TextView tv1, TextView... tv2s) {
        if (TextUtils.isEmpty(tv1.getText().toString())) {
            return true;
        }
        for (TextView tv2 : tv2s) {
            if (TextUtils.isEmpty(tv2.getText().toString())) {
                return true;
            }
        }

        return false;

    }


    /**
     * 获取设备制造商
     *
     * @return
     */
    public static String getFactory() {
        return Build.MANUFACTURER;
    }


    public static void signOut(FragmentActivity context) {
//        App.getInstance().deleteAlias();
//        User.get().loginOut();
//        new ShareManager(context).deleteOauth();
//        EventBus.getDefault().post(new Events.UserChangedEvent(Events.UserChangedEvent.SIGN_OUT));
    }

    @SuppressWarnings("RestrictedApi")
    public static void showError(final FragmentActivity context, Throwable ex) {
        if (ex instanceof ApiException) {
            ApiException apiException = (ApiException) ex;

            if (apiException.getMessage().isEmpty() || apiException.getErrorCode() == 404) {
                return;
            }
            if (apiException.getErrorCode() == ApiException.AUTHORIZATION_ERROR) {
                Utils.signOut(context);
                if (reLoginDialog == null) {
                    reLoginDialog = new CommonDialog(context, "登录信息已过期，请重新登录");
                    GenericLifecycleObserver lifecycleObserver = new GenericLifecycleObserver() {
                        @Override
                        public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
                            if (source.getLifecycle().getCurrentState() == DESTROYED) {
                                if (reLoginDialog != null && reLoginDialog.isShowing()) {
                                    reLoginDialog.dismiss();
                                }
                                source.getLifecycle().removeObserver(this);
                            }
                        }
                    };
                    context.getLifecycle().addObserver(lifecycleObserver);
                }
                if (!reLoginDialog.isShowing()) {
                    reLoginDialog.show();
//                    reLoginDialog.setOnPositiveButtonClickListener(dialog -> Utils.startLogin(context));
                    reLoginDialog.setOnDismissListener(dialog -> reLoginDialog = null);
                }
                return;
            }
        }

        T.showShort(context, parseMessage(ex));
    }

    public static int parseInt(String value) {
        try {

            return Integer.parseInt(value);
        } catch (Exception e) {
            return 0;
        }
    }

    public static String packUrls(List<String> urls) {
        if (!isEmpty(urls)) {
            StringBuilder buffer = new StringBuilder();
            for (String url : urls) {
                buffer.append(url).append(",");
            }
            buffer.deleteCharAt(buffer.length() - 1);
            return buffer.toString();
        }
        return null;
    }

    public static File[] imageUris2Files(List<String> filePaths) {
        File[] files = new File[filePaths.size()];
        for (int i = 0; i < files.length; i++) {
            files[i] = new File(filePaths.get(i));
        }
        Log.i("UploadManager", "file:" + files);
        return files;
    }

    public static void openUrl(Context context, String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        context.startActivity(intent);
    }

    public static String getNotNullUserId() {
        return User.get().getId() == null ? "0" : User.get().getId();
    }


    public static String getPhaseString(int phaseNum) {
        return String.format("第%s期", Utils.getPhaseNumString(phaseNum));
    }

    public static String getPhaseNumString(int phaseNum) {
        if (phaseNum < 10) {
            return "00" + phaseNum;
        } else if (phaseNum < 100) {
            return "0" + phaseNum;
        }
        return String.valueOf(phaseNum);
    }

    public static String calculateCountdownText(int seconds) {
        StringBuilder buffer = new StringBuilder();
        if (seconds >= 3600) {
            int hour = seconds / 3600;
            seconds = seconds % 3600;
            buffer.append(hour).append("小时");
        }
        if (seconds > 60) {
            int minutes = seconds / 60;
            buffer.append(minutes).append("分");
            seconds = seconds % 60;
        }
        buffer.append(seconds).append("秒");
        return buffer.toString();
    }

    public interface Callback {
        void callBack(boolean exist);
    }

    public static void isAppInstalled(final Context context, final String packageName, final Callback callback) {

        new AsyncTask<Void, Void, Void>() {
            private boolean result = false;

            @Override
            protected void onPreExecute() {
            }

            @Override
            protected Void doInBackground(Void... params) {
                try {
                    final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
                    List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
                    if (pinfo != null) {
                        for (int i = 0; i < pinfo.size(); i++) {
                            String pn = pinfo.get(i).packageName;
                            if (packageName.equals(pn)) {
                                result = true;
                                break;
                            }
                        }
                    }
                } catch (Exception e) {
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void r) {
                callback.callBack(result);
            }
        }.execute();

    }




    public static String formatMoney(int amounts) {
        double doubleAmounts = amounts / (double) 100;
        DecimalFormat formarter = new DecimalFormat();
        formarter.setMaximumFractionDigits(3);
        formarter.setGroupingSize(0);
        formarter.setRoundingMode(RoundingMode.FLOOR);
        return formarter.format(doubleAmounts);
    }

    public static double formatMoneyD(double amounts) {
        double doubleAmounts = amounts / (double) 100;
        return doubleAmounts;
    }

    public static String formatDisplay(int li) {
        return "¥" + formatMoney(li);
    }
//    public static float valueOfMoney(float value) {
//        return Float.valueOf(formatMoney(value));
//    }

//    public static String formatRmb(float amount) {
//        return String.format(App.getInstance().getResources().getString(R.string.rmb), amount);
//    }
//
//    public static String formatYuan(float amount) {
//        return String.format(App.getInstance().getResources().getString(R.string.yuan), amount);
//    }


    public static String parseName(String url) {
        int lastPos = url.lastIndexOf("/");
        if (lastPos != -1) {
            return url.substring(lastPos + 1);
        }
        return url;
    }

    /**
     * Fragment跳转， 将一个layout替换为新的fragment。
     *
     * @param fm
     * @param replaceLayoutId
     * @param fragmentClass
     * @return
     */
    public static Fragment replace(FragmentManager fm, int replaceLayoutId, Class<? extends Fragment> fragmentClass) {
        return replace(fm, fragmentClass, replaceLayoutId, fragmentClass.getSimpleName(), null);
    }

    public static Fragment replace(FragmentManager fm, int replaceLayoutId, Class<? extends Fragment> fragmentClass, String tag, Bundle args) {
        return replace(fm, fragmentClass, replaceLayoutId, tag, args);
    }

    /**
     * Fragment跳转， 将一个layout替换为新的fragment。
     *
     * @param fm
     * @param fragmentClass
     * @param tag
     * @param args
     * @return
     */
    public static Fragment replace(FragmentManager fm, Class<? extends Fragment> fragmentClass, int replaceLayoutId, String tag,
                                   Bundle args) {
        // mIsCanEixt = false;
        Fragment fragment = fm.findFragmentByTag(tag);
        boolean isFragmentExist = true;
        if (fragment == null) {
            try {
                isFragmentExist = false;
                fragment = fragmentClass.newInstance();
                if (args != null)
                    fragment.setArguments(args);
                else {
                    fragment.setArguments(new Bundle());
                }

            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            if (args != null) {
                if (fragment.getArguments() != null)
                    fragment.getArguments().putAll(args);
                else
                    fragment.setArguments(args);
            }
        }
        if (fragment == null)
            return null;
        if (fragment.isAdded()) {
            // fragment.onResume();
            return fragment;
        }
        FragmentTransaction ft = fm.beginTransaction();
        if (isFragmentExist) {
            ft.replace(replaceLayoutId, fragment);
        } else {
            ft.replace(replaceLayoutId, fragment, tag);
        }

        ft.addToBackStack(tag);
        ft.commitAllowingStateLoss();
        return fragment;
    }

    public static boolean isAppInBackground(Context context) {
        boolean isInBackground = true;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) { // Android5.0及以后的检测方法
            List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
            if (!Utils.isEmpty(runningProcesses)) {
                for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
                    //前台程序
                    if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                        for (String activeProcess : processInfo.pkgList) {
                            if (activeProcess.equals(context.getPackageName())) {
                                isInBackground = false;
                            }
                        }
                    }
                }
            }
        } else {
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equals(context.getPackageName())) {
                isInBackground = false;
            }
        }
        return isInBackground;
    }

    /*
     * Java文件操作 获取不带扩展名的文件名
     */
    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static boolean isPhoneNum(String phoneNumber) {
        if (TextUtils.isEmpty(phoneNumber)) {
            return false;
        }
        try {
            Pattern p = Pattern.compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9])|(92[0-9])|(98[0-9])|(16[0-9])|(19[0-9]))\\d{8}$");
            Matcher m = p.matcher(phoneNumber);
            return m.matches();
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 密码大于等于6位
     *
     * @param password
     * @return
     */
    public static boolean isPasswordValid(String password) {
        return password.length() >= 6 && password.length() <= 18;
    }

    /**
     * 验证用户 名是否有效
     */
    public static boolean validatePhone(String phoneNum) {
        if (Utils.isPhoneNum(phoneNum)) {
            return true;
        } else {
            // userInputPrompt.setText(R.string.enter_right_phone_num);
            T.showShort(R.string.enter_right_phone_num);
            return false;
        }
    }


    /**
     * 浮点数除法，计算金额使用 a/b
     *
     * @param a
     * @param b
     * @return 返回String类型
     */
    public static String floatDivideDefaultNumString(String a, String b) {
        if (Double.parseDouble(a) == 0 || Double.parseDouble(b) == 0) {
            return "0";
        }
        BigDecimal result = new BigDecimal(a).divide(new BigDecimal(b));
        return result.toString();
    }


    /**
     * @param
     * @return
     */
    public static String formatNumber(String number) {
        if (Double.parseDouble(number) > 1) {
            return String.format("%.2f", Double.parseDouble(number)) + "Km";
        } else if (Double.parseDouble(number) > 0) {
            return (int) Math.floor(Double.parseDouble(floatMultiplyString(number, "1000"))) + "m";
        } else {
            return "";
        }
    }


    /**
     * 浮点数乘法，计算金额时使用 a*b
     *
     * @param a
     * @param b
     * @return 返回String类型
     */
    public static String floatMultiplyString(String a, String b) {
        if (a == null || b == null || Double.parseDouble(a) == 0 || Double.parseDouble(b) == 0) {
            return "0";
        }
        BigDecimal result = new BigDecimal(a).multiply(new BigDecimal(b));
        return result.toString();
    }


    /**
     * 验证密码
     */
    public static boolean validatePassword(String password) {
        if (!Utils.isPasswordValid(password)) {
            // userInputPrompt.setText(R.string.incorrect_passowrd_length);
            T.showShort(R.string.incorrect_passowrd_length);
            return false;
        }
        return true;
    }

    public static void jumpToWx(Context context) {
        // jump to wechat
        ComponentName name = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
        try {
            Intent intent = new Intent();
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(name);
            context.startActivity(intent);
        } catch (Exception e) {
            T.showShort("微信未安装");
            e.printStackTrace();
        }
    }

    public static long parseLong(String value) {
        try {

            return Long.parseLong(value);
        } catch (Exception e) {
            return 0;
        }
    }

    public static String downloadApk(String url) {
        DownloadManager manager = Session.getInstance().getDownloadManager();
        DownloadInfo info = manager.query(url);
        String key = mappingId(url);
        if (info != null) {
            if (Downloads.isStatusSuccess(info.mStatus)) {

                File apkPath = new File(info.mFileName);

                if (!apkPath.exists() || !apkPath.isFile()) {
                    manager.remove(info.mId);
                    info = null;
                }
            } else {
                manager.remove(info.mId);
                info = null;
            }

        }
        if (info == null) {
//            File directory = new File(Environment.DIRECTORY_DOWNLOADS, "com.tulele.download");
//            if (!directory.exists()) {
//                directory.mkdir();
//            }
            DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
            request.setTitle(key);
            request.setShowRunningNotification(false);
            request.setMimeType(com.mozillaonline.providers.downloads.Constants.MIMETYPE_APK);
            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "/");
            request.setUid(url);
            request.setDescription(String.valueOf(System.currentTimeMillis()));
            manager.enqueue(request);
            return null;
        }

        return Downloads.isStatusSuccess(info.mStatus) ? info.mFileName : null;

    }

    private static String mappingId(String path) {
        return Utils.md5(path) + ".apk";
    }


}

